package com.hmkj.web.controller.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.api.lianlian.PartnerConfig;
import com.hmkj.core.api.lianlian.PaymentInfo;
import com.hmkj.core.api.lianlian.util.HttpRequestSimple;
import com.hmkj.core.api.lianlian.util.YinTongUtil;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.pay.PayResult;
import com.hmkj.core.po.amount.Recharge;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.user.UserBank;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.core.service.user.UserBankService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import com.xiaoleilu.hutool.util.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

@Api(description = "连连支付")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/pay/lianlian")
public class LianLianPayController extends GenericController<Integer, Recharge> {

    @Resource
    private UserService userService;

    @Resource
    private UserBankService userBankService;

    @Resource
    private RechargeService rechargeService;

    /**
     * 银行卡卡bin信息查询
     *
     * @param cardNo 银行卡
     */
    @ApiOperation(value = "银行卡卡bin信息查询", notes = "银行卡卡bin信息查询")
    @ResponseBody
    @RequestMapping(value = "/queryCardBin", method = RequestMethod.POST)
    public ResultEntity queryCardBin(String cardNo) throws Exception {
        JSONObject reqObj = new JSONObject();
        reqObj.put("oid_partner", PartnerConfig.OID_PARTNER);
        reqObj.put("card_no", cardNo);
        reqObj.put("sign_type", PartnerConfig.SIGN_TYPE);
        String sign = YinTongUtil.addSign(reqObj, PartnerConfig.TRADER_PRI_KEY,
                PartnerConfig.MD5_KEY);
        reqObj.put("sign", sign);
        String reqJSON = reqObj.toString();
        System.out.println("银行卡卡bin信息查询请求报文[" + reqJSON + "]");
        String resJSON = HttpRequestSimple.getInstance().postSendHttp(PartnerConfig.QUERY_BANKCARD_URL, reqJSON);
        System.out.println("银行卡卡bin信息查询响应报文[" + resJSON + "]");
        JSONObject resJson = JSONObject.parseObject(resJSON);
        Map<String, Object> map = new HashMap<>();
        map.put("bankCode", resJson.getString("bank_code"));
        map.put("bankName", resJson.getString("bank_name"));
        map.put("cardType", resJson.getString("card_type"));
        return ok("查询成功", map);
    }


    /**
     * 用户已绑定银行列表查询(本地绑定的银行列表)
     */
    @ApiOperation(value = "用户已绑定银行列表", notes = "用户已绑定银行列表")
    @ResponseBody
    @RequestMapping(value = "/getBankCardListJson", method = RequestMethod.POST)
    public ResultEntity getBankCardListJson() throws Exception {
        User user = userService.selectByPrimaryKey(getLoginUser().getId());
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(user.getRealName()) || StringUtils.isNotBlank(user.getIdCard())) {
            map.put("realName", user.getRealName());
            map.put("idCard", user.getIdCard());
        } else {
            throw new BussinessException("请先实名认证");
        }
        List<UserBank> banks = userBankService.select(new UserBank(ub -> {
            ub.setUserId(user.getId());
            ub.setDelFlag(UserBank.DELFLAG.NORMAL.code);
        }));
        if (CollectionUtil.isNotEmpty(banks)) {
            map.put("bankList", banks);
        } else {
            throw new BussinessException("请先添加银行卡");
        }
        return ok("查询成功", map);
    }


    /**
     * 用户已绑定银行列表查询(先查询连连绑定的银行列表)
     */
    @ApiOperation(value = "用户已绑定银行列表", notes = "用户已绑定银行列表")
    @ResponseBody
    @RequestMapping(value = "/queryBankCardListJson", method = RequestMethod.POST)
    public ResultEntity queryBankCardListJson() throws Exception {
        User user = userService.selectByPrimaryKey(getLoginUser().getId());
        Map<String, Object> map1 = new HashMap<>();
        if (StringUtils.isNotBlank(user.getRealName())) {
            map1.put("realName", user.getRealName());
        }
        if (StringUtils.isNotBlank(user.getId())) {
            map1.put("idCard", user.getIdCard());
        }
        List<Map<String, Object>> list = queryBankCardList(user);
        map1.put("bankList", list);
        return ok("查询成功", map1);
    }

    /**
     * 查询用户已经支付成功的银行卡信息
     *
     * @param user 登录用户
     * @throws Exception ex
     */
    private List<Map<String, Object>> queryBankCardList(User user) throws Exception {
        if (null == user) {
            return null;
        }
        JSONObject reqObj = new JSONObject();
        reqObj.put("oid_partner", PartnerConfig.OID_PARTNER);
        reqObj.put("user_id", user.getId());
        reqObj.put("offset", "0");
        reqObj.put("sign_type", PartnerConfig.SIGN_TYPE);
        reqObj.put("pay_type", "D");
        String sign = YinTongUtil.addSign(reqObj, PartnerConfig.TRADER_PRI_KEY, PartnerConfig.MD5_KEY);
        reqObj.put("sign", sign);
        String reqJSON = reqObj.toString();
        System.out.println("用户已绑定银行列表查询请求报文[" + reqJSON + "]");
        String resJSON = HttpRequestSimple.getInstance().postSendHttp(PartnerConfig.QUERY_USER_BANKCARD_URL, reqJSON);
        System.out.println("用户已绑定银行列表查询响应报文[" + resJSON + "]");

        //用户实名认证
        JSONObject resObj = JSONObject.parseObject(resJSON);
        JSONArray jsonArray = JSON.parseArray(resObj.getString("agreement_list"));
        List<Map<String, Object>> list = new ArrayList<>();
        if (jsonArray != null && jsonArray.size() > 0) {
            Map<String, Object> m;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                m = new HashMap<>(10);
                m.put("noAgree", jsonObject.getString("no_agree"));
                m.put("cardNo", jsonObject.getString("card_no"));
                m.put("bankCode", jsonObject.getString("bank_code"));
                m.put("bankName", jsonObject.getString("bank_name"));
                m.put("cardType", jsonObject.getString("card_type"));
                m.put("bindMobile", jsonObject.getString("bind_mobile"));
                list.add(m);
            }
        }
        return list;
    }

    /**
     * WAP认证支付接口
     */
    @ApiOperation(value = "WAP认证支付接口", notes = "WAP认证支付接口")
    @RequestMapping(value = "/wapAuthPay", method = RequestMethod.POST)
    public void wapAuthPay(HttpServletResponse response, @ApiParam("银行id") @RequestParam Integer bankId, @ApiParam("充值金额") @RequestParam String amount) throws Exception {

        //uuid 充值返回请求页面结果的参数
        String hmTk = UUID.randomUUID().toString();
        String html;
        try {
            html = getPayHtml(rechargeService.doRechargeByLianLian(getLoginUser().getId(), bankId, hmTk, amount));
        } catch (BussinessException e) {
            redisService.put(CacheID.PAY_RESULT + hmTk, PayResult.failed(e.getMessage(), ""), 30 * 60);
            html = getPayErrorHtml(hmTk);
        } catch (Exception e) {
            redisService.put(CacheID.PAY_RESULT + hmTk, PayResult.failed("系统繁忙，请稍后再试", ""), 30 * 60);
            html = getPayErrorHtml(hmTk);
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(html);
        out.flush();
        out.close();
    }

    private String getPayHtml(PaymentInfo paymentInfo) {
//        return "正在跳转。。。<br/>" +
//                "<form style = \"display:none;\" id=\"lianLianPaySubmit\" name=\"lianLianPaySubmit\" action=\"" + PartnerConfig.WAP_PAY_URL + "\" method=\"post\">\n" +
//                "<input type=\"text\" name=\"req_data\" value=\"" + JSON.toJSONString(paymentInfo) + "\"/><br/>" +
//                "<input type=\"submit\" value=\"" + "确定" + "\" style=\"display;\"></form>" +
//                "<script>document.forms['lianLianPaySubmit'].submit();</script>";

        return "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\" />\n" +
                "<title>快捷支付</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "快捷支付页面跳转中...\n" +
                "<form style = \"display:none;\" action=\"" + PartnerConfig.WAP_PAY_URL + "\" method=\"post\">\n" +
                "<input type=\"text\" name=\"req_data\" value='" + JSON.toJSONString(paymentInfo) + "'>\n" +
                "</form>\n" +
                "<script>document.forms[0].submit();</script>\n" +
                "</body>\n" +
                "</html>";
    }

    private String getPayErrorHtml(String hmTk) {
//        return "正在跳转。。。<br/>" +
//                "<form style = \"display:none;\" id=\"lianLianPaySubmit\" name=\"lianLianPaySubmit\" action=\"" + redisService.get(ConfigNID.WEB_SERVER_URL) + "result?hm_tk=" + hmTk + "\" method=\"post\">\n" +
//                "</form><script>document.forms['lianLianPaySubmit'].submit();</script>";

        return "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\" />\n" +
                "<title>快捷支付</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "快捷支付页面跳转中...\n" +
                "<form style = \"display:none;\" action=\"" + redisService.get(ConfigNID.WEB_SERVER_URL) + "result?hm_tk=" + hmTk + "\" method=\"post\">\n" +
                "</form>\n" +
                "<script>document.forms[0].submit();</script>\n" +
                "</body>\n" +
                "</html>";
    }


}
